package com.ly.ssh.dao.impl;

import com.ly.ssh.dao.AddressDao;
import com.ly.ssh.entity.Address;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by XRom
 * On 11/16/2017.11:55 PM
 */
@Repository
public class AddressDaoImpl implements AddressDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.openSession();
    }

    @Override
    public Address load(Integer id) {
        return (Address) getCurrentSession().load(Address.class, id);
    }

    @Override
    public Address get(Integer id) {
        return (Address) getCurrentSession().get(Address.class, id);
    }

    @Override
    public List<Address> findAll() {
        Session session = sessionFactory.getCurrentSession();
        String hql = "from Address";
        Query query = session.createQuery(hql);
        List<Address> persons = query.list();
        return persons;
    }

    @Override
    public void persist(Address entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public Integer save(Address entity) {
        return (Integer) getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(Address entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(Integer id) {
        Address person = load(id);
        getCurrentSession().delete(person);
    }

    @Override
    public void flush() {
        getCurrentSession().flush();
    }
}
